package com.gitee.liuzhi.demo.juc;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ForkJoinPool;

/**
 * @Author liuzhi
 * @Date 2023/9/6 20:47
 * @Version 1.0
 * @Description
 */
@Slf4j
public class DynamicForkJoinPoolDemo {

    public static void main(String[] args) {
        int size = 100;
        ForkJoinPool forkJoinPool = DynamicForkJoinPoolDemo.getParallelismPool();
        List<CompletableFuture<?>> completableFutures = Lists.newArrayListWithCapacity(size);
        for (int i = 0; i < size; i++) {
            CompletableFuture<Void> completableFuture =
                    CompletableFuture.runAsync(() -> log.info(Thread.currentThread().getName()),forkJoinPool);
            completableFutures.add(completableFuture);
        }
        try {
            CompletableFuture.allOf(completableFutures.toArray(CompletableFuture[]::new)).get();
        } catch (Exception e) {
            log.error(String.format("runAsync error, message:[%s]",e.getMessage()),e);
        }

    }



    private static ForkJoinPool COMMON_POOL;

    private static ForkJoinPool PARALLELISM_POOL;

    private final static Integer PARALLELISM = 2;

    private DynamicForkJoinPoolDemo() {}

    public static ForkJoinPool getCommonPool() {
        if (Objects.isNull(COMMON_POOL)) {
            COMMON_POOL = ForkJoinPool.commonPool();
            log.info("commonPool init success");
        }
        return COMMON_POOL;
    }

    public static ForkJoinPool getParallelismPool() {
        if (Objects.isNull(PARALLELISM_POOL)) {
            PARALLELISM_POOL = new ForkJoinPool(PARALLELISM);
            log.info("parallelismPool init success");
        }
        return PARALLELISM_POOL;
    }

}
